#!/bin/bash
#
# Power 12V Output Control
#

GPIO_PWR12V=267

SYSFS_GPIO=/sys/class/gpio
SYSFS_PWR12V=${SYSFS_GPIO}/gpio${GPIO_PWR12V}

function usage()
{
	echo -e "\nUsage: $0 [on/off]]\n"
	echo -e "  $(basename $0) -------- Get current power status"
	echo -e "  $(basename $0) on  ---- Set power on"
	echo -e "  $(basename $0) off ---- Set power off\n"
}

function gpio_init()
{
	if [[ ! -d ${SYSFS_PWR12V} ]]; then
		echo ${GPIO_PWR12V} > ${SYSFS_GPIO}/export
	fi
}

function power_operate()
{
	if [[ $# -lt 1 ]]; then
		local value=$(cat ${SYSFS_PWR12V}/value)

		if [[ ${value} -eq 1 ]]; then
			echo -e "[INFO] Power 12V is ON."
		elif [[ ${value} -eq 0 ]]; then
			echo -e "[INFO] Power 12V is OFF."
		else
			echo -e "[INFO] Unknown power state."
		fi
	else
		case $1 in
			"on" | "ON")
				echo 1 > ${SYSFS_PWR12V}/value
				echo -e "[INFO] Power 12V turn ON."
				;;
			"off" | "OFF")
				echo 0 > ${SYSFS_PWR12V}/value
				echo -e "[INFO] Power 12V turn OFF."
				;;
			*)
				echo -e "[ERROR] Unknown power operation: $1, do nothing!"
				usage
				exit 1
				;;
		esac
	fi
}

if [[ $(id -u) -ne 0 ]]; then
	echo -e "[ERROR] Please run as root!"
	usage
	exit 1
fi

gpio_init

if [[ $# -eq 0 ]]; then
	value=$(cat ${SYSFS_PWR12V}/value)

	case ${value} in
		"1")
			echo -e "[INFO] Power 12V is ON."
			;;
		"0")
			echo -e "[INFO] Power 12V is OFF."
			;;
		*)
			echo -e "[INFO] Unknown power state."
			;;
	esac
else
	case $1 in
		"on" | "ON")
			echo 1 > ${SYSFS_PWR12V}/value
			echo -e "[INFO] Power 12V turn ON."
			;;
		"off" | "OFF")
			echo 0 > ${SYSFS_PWR12V}/value
			echo -e "[INFO] Power 12V turn OFF."
			;;
		*)
			echo -e "[ERROR] Unknown power operation: $1, do nothing!"
			usage
			exit 1
			;;
	esac
fi
